package com.toefl.speaking.activity;

import java.io.File;

import org.json.JSONObject;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.toefl.speaking.R;
import com.toefl.speaking.activity.base.BaseActivity;
import com.toefl.speaking.business.QuestionBusiness;
import com.toefl.speaking.dao.bean.QuestionBean;
import com.toefl.speaking.handler.QuestionHandler;
import com.toefl.speaking.helper.CustomDialog;
import com.toefl.speaking.helper.RoundProgressBar;
import com.toefl.speaking.util.AppConstans;

public class QuestionActivity extends BaseActivity {

	public static QuestionBean questionBean;

	private TextView content;
	private Button btn_read, btn_listent, btn_speak;
	private RelativeLayout read_layout, listent_layout, speak_layout;
	public static int questionID;
	private MediaPlayer mp;

	private Button btn_listent_control;
	private SeekBar slider;
	private boolean isStart = false;
	private TextView tv_totle_time, tv_leave_time;
	private RoundProgressBar round_bar;

	private Button btn_record;
	private int isPreparing = 0;

	private MediaRecorder recorder;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.context = QuestionActivity.this;
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initUI() {
		super.setContentView(R.layout.question_layout);
		content = (TextView) findViewById(R.id.content);
		btn_read = (Button) this.findViewById(R.id.question_title_bar).findViewById(R.id.btn_read);
		btn_listent = (Button) this.findViewById(R.id.question_title_bar).findViewById(R.id.btn_listent);
		btn_speak = (Button) this.findViewById(R.id.question_title_bar).findViewById(R.id.btn_speak);
		read_layout = (RelativeLayout) findViewById(R.id.read_layout);
		listent_layout = (RelativeLayout) findViewById(R.id.listent_layout);
		speak_layout = (RelativeLayout) findViewById(R.id.speak_layout);
		btn_listent_control = (Button) findViewById(R.id.btn_listent_control);
		slider = (SeekBar) findViewById(R.id.slider);
		tv_totle_time = (TextView) findViewById(R.id.tv_totle_time);
		tv_leave_time = (TextView) findViewById(R.id.tv_leave_time);
		round_bar = (RoundProgressBar) findViewById(R.id.round_bar);
		btn_record = (Button) findViewById(R.id.btn_record);
		super.initUI();
	}

	@Override
	protected void initData() {
		Intent intent = getIntent();
		questionID = intent.getIntExtra("question_id", 0);
		questionBean = new QuestionBean();
		questionBean.question_id = questionID;
		questionBean.question_type = intent.getIntExtra("question_type", 0);
		postGetQuestionDetail(intent.getIntExtra("question_id", 0));
		mp = new MediaPlayer();
		super.initData();
	}

	@Override
	protected void setUI() {
		ButtonsOnClickListener listener = new ButtonsOnClickListener();
		// content = (TextView) findViewById(R.id.content);
		content.setText(questionBean.question_content);
		btn_read.setOnClickListener(listener);
		btn_listent.setOnClickListener(listener);
		btn_speak.setOnClickListener(listener);
		btn_listent_control.setOnClickListener(listener);
		btn_record.setOnClickListener(listener);
		mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				// slider.
				// TODO 播放结束后

			}

		});
		slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				if (fromUser == true) {
					mp.seekTo(progress);
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}
		});
		super.setUI();
	}

	Handler handler = new Handler();
	Runnable updateThread = new Runnable() {
		public void run() {
			slider.setProgress(mp.getCurrentPosition());
			int aduioTime = mp.getCurrentPosition() / 1000;
			String showTotalTime = aduioTime / 60 + ":" + aduioTime % 60;
			tv_leave_time.setText(showTotalTime);
			handler.postDelayed(updateThread, 100);
		}
	};

	@Override
	protected void userOnPost() {
		try {
			String aduioPath = Environment.getExternalStorageDirectory().getAbsolutePath() + AppConstans.PROJECT_PATH
					+ AppConstans.ADUIO_PATH + "/" + questionID + ".mp3";
			Uri aduioUri = Uri.parse(aduioPath);
			mp = MediaPlayer.create(this, aduioUri);
			slider.setMax(mp.getDuration());
			int aduioTime = mp.getDuration() / 1000;
			String showTotalTime = aduioTime / 60 + ":" + aduioTime % 60;
			// String showTotalTime = aduioTime % 60 + ":" + aduioTime / 60;
			tv_totle_time.setText(showTotalTime);
			tv_leave_time.setText(showTotalTime);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		super.userOnPost();
	}

	@Override
	public void userDoInBackground() {
		File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + AppConstans.PROJECT_PATH
				+ AppConstans.ADUIO_PATH + "/" + questionID + ".mp3");
		if (!file.exists()) {
			postGetQuestionAudio(questionID);
		}
		super.userDoInBackground();
	}

	private class ButtonsOnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_read:
				read_layout.setVisibility(View.VISIBLE);
				listent_layout.setVisibility(View.GONE);
				speak_layout.setVisibility(View.GONE);
				break;
			case R.id.btn_listent:
				read_layout.setVisibility(View.GONE);
				listent_layout.setVisibility(View.VISIBLE);
				speak_layout.setVisibility(View.GONE);
				getUserAsyncTask().execute();
				break;
			case R.id.btn_speak:
				read_layout.setVisibility(View.GONE);
				listent_layout.setVisibility(View.GONE);
				speak_layout.setVisibility(View.VISIBLE);
				break;
			case R.id.btn_listent_control:
				if (isStart) {
					mp.pause();
					handler.removeCallbacks(updateThread);
				} else {
					mp.start();
					handler.post(updateThread);
				}
				isStart = !isStart;
				break;
			case R.id.btn_record:
				btn_record.setEnabled(false);
				if (!btn_record.isEnabled()) {

				}
				round_bar.startCartoom(8);
				MyCount mc = new MyCount(8 * 1000, 10);
				mc.start();

				break;
			}
		}
	}

	/**
	 * 获取题目详情内容+保存题目信息
	 * @param questionId
	 */
	public void postGetQuestionDetail(int questionId) {
		QuestionHandler questionHandler = QuestionHandler.instance();
		String result = null;
		try {
			QuestionBean temp = QuestionBusiness.getQuestionInfoByQID(String.valueOf(questionId));
			if (temp != null) {
				questionBean = temp;
			} else {
				result = questionHandler.postQuestionDetail(questionId);
				JSONObject jsonResult = new JSONObject(result).getJSONObject("QuestionDetail");
				// questionBean = new QuestionBean();
				questionBean.question_id = questionId;
				questionBean.question_title = jsonResult.getString("Topic");
				questionBean.question_content = jsonResult.getString("Content");
				boolean a = QuestionBusiness.saveUpdateCustomer(questionBean);
				System.out.println(a ? "保存题目内容成功" : "保存题目内容失败");
			}
		} catch (Exception e) {

		}
	}

	public void postGetQuestionAudio(int questionId) {
		QuestionHandler questionHandler = QuestionHandler.instance();
		try {
			QuestionBean temp = QuestionBusiness.getQuestionInfoByQID(String.valueOf(questionId));
			if (temp != null) {
				if (temp.question_listent_path != null) {
					questionBean.question_listent_path = temp.question_listent_path;
				} else {
					questionHandler.postDownloadQuestionAudio(questionId);
					questionBean.question_listent_path = Environment.getExternalStorageDirectory().getAbsolutePath()
							+ AppConstans.PROJECT_PATH + AppConstans.ADUIO_PATH + questionBean.question_id + ".mp3";
				}
			} else {
				boolean a = QuestionBusiness.saveUpdateCustomer(questionBean);
				postGetQuestionAudio(questionId);
				// System.out.println(a ? "保存题目内容成功" : "保存题目内容失败");
			}
			// if(下载音频成功 并保存存与数据库) TODO

		} catch (Exception e) {

		}
	}

	/* 定义一个倒计时的内部类 */
	class MyCount extends CountDownTimer {

		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			isPreparing++;
			round_bar.setText(String.valueOf("0"));
			round_bar.stopCartoom();
			round_bar.setProgress(0);
			if (isPreparing == 1) {
				recorderStart();
				MyCount mc = new MyCount(8 * 1000, 10);
				mc.start();
				round_bar.startCartoom(8);
			} else if (isPreparing == 2) {
				recorderStopAndSave();
				// playVideo();
				isPreparing = 0;
				showDaillog();
				btn_record.setEnabled(true);
				// DialogHelper.showToast2(QuestionActivity.this, null, "我要....");
			}
		}

		@Override
		public void onTick(long millisUntilFinished) {

			long totalSeconds = millisUntilFinished / 1000;
			// round_bar.setProgress((int) (totalSeconds * 100 / totalTime));
			round_bar.setText(String.valueOf(totalSeconds));
		}
	}

	/**
	 * 开始录音
	 */
	private void recorderStart() {

		try {
			recorder = new MediaRecorder();
			recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
			recorder.setAudioEncoder(3);
			String path = Environment.getExternalStorageDirectory() + File.separator + "test.mp3";
			if (!new File(path).exists())
				new File(path).createNewFile();
			recorder.setOutputFile(path);
			recorder.prepare();
			recorder.start(); // Recording is now started
		} catch (Exception e) {
			Log.e("", "prepare() failed");
		}
	}

	/**
	 * 录音结束
	 */
	private void recorderStopAndSave() {
		recorder.stop();
		recorder.release();
		recorder = null;
	}

	/**
	 * 播放录音
	 */
	public void playVideo() {
		String path = Environment.getExternalStorageDirectory() + File.separator + "test.mp3";
		MediaPlayer mediaPlayer = new MediaPlayer();
		try {
			mediaPlayer.setDataSource(QuestionActivity.this, Uri.parse("file://" + path));
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	private void showDaillog() {
		CustomDialog dialog = new CustomDialog(QuestionActivity.this, CustomDialog.AlertType.DIALOG_ALERT);
		dialog.setMessage("我要... ...");
		dialog.show();
	}

}
